import React, { useState, useEffect } from 'react';
import { View, Text, Picker } from '@tarojs/components';
import Taro from '@tarojs/taro';
import styles from './index.module.scss';

// 工具函数
const parseTime = (timeStr: string): [number, number] => {
  const [hour, minute] = timeStr.split(':').map(Number);
  return [hour || 0, minute || 0];
};

const calculateDuration = (startTime: string, endTime: string): string => {
  const [startHour, startMinute] = parseTime(startTime);
  const [endHour, endMinute] = parseTime(endTime);

  const startMinutes = startHour * 60 + startMinute;
  const endMinutes = endHour * 60 + endMinute;

  const durationMinutes = endMinutes - startMinutes;
  const hours = Math.floor(durationMinutes / 60);
  const minutes = durationMinutes % 60;

  if (hours > 0 && minutes > 0) {
    return `${hours}小时${minutes}分钟`;
  } else if (hours > 0) {
    return `${hours}小时`;
  } else {
    return `${minutes}分钟`;
  }
};

interface BusinessTimePickerProps {
  value?: string; // 格式: "09:00~18:00"
  onChange?: (value: string) => void;
  placeholder?: string;
  defaultStartTime?: string; // 默认开始时间，格式: "09:00"
  defaultEndTime?: string; // 默认结束时间，格式: "18:00"
  disabled?: boolean; // 是否禁用
  showDuration?: boolean; // 是否显示营业时长
}

const BusinessTimePicker: React.FC<BusinessTimePickerProps> = ({
  value = '',
  onChange,
  placeholder = '请选择营业时间',
  defaultStartTime = '09:00',
  defaultEndTime = '18:00',
  disabled = false,
  showDuration = false,
}) => {
  // 解析默认时间并设置初始索引（7列：时、:、分、~、时、:、分）
  const getDefaultIndices = () => {
    const [startHour, startMinute] = defaultStartTime.split(':').map(Number);
    const [endHour, endMinute] = defaultEndTime.split(':').map(Number);
    return [startHour, 0, startMinute, 0, endHour, 0, endMinute]; // 分隔符列固定为0
  };

  const [selectedIndices, setSelectedIndices] = useState(getDefaultIndices());

  // 生成时间选项 - 7列数据，包含时分分隔符
  const timeRange = [
    Array.from({ length: 24 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0'),
    })), // 开始时
    [{ label: ':', value: ':' }], // 时分分隔符
    Array.from({ length: 60 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0'),
    })), // 开始分
    [{ label: '～', value: '~' }], // 时间段分隔符
    Array.from({ length: 24 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0'),
    })), // 结束时
    [{ label: ':', value: ':' }], // 时分分隔符
    Array.from({ length: 60 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0'),
    })), // 结束分
  ];

  // 简化的时间数组用于计算
  const simpleTimeRange = [
    Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0')),
    Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0')),
    Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0')),
    Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0')),
  ];

  // 解析传入的值并更新选择器索引
  useEffect(() => {
    if (value && value.includes('~')) {
      const [start, end] = value.split('~');
      if (start && start.includes(':') && end && end.includes(':')) {
        const [sHour, sMinute] = start.split(':');
        const [eHour, eMinute] = end.split(':');

        const startHourIdx = parseInt(sHour);
        const startMinuteIdx = parseInt(sMinute);
        const endHourIdx = parseInt(eHour);
        const endMinuteIdx = parseInt(eMinute);

        setSelectedIndices([
          startHourIdx,
          0, // : 分隔符固定为0
          startMinuteIdx,
          0, // ~ 分隔符固定为0
          endHourIdx,
          0, // : 分隔符固定为0
          endMinuteIdx,
        ]);
      }
    }
  }, [value]);

  // 验证时间合理性
  const validateTime = (
    startHour: string,
    startMinute: string,
    endHour: string,
    endMinute: string,
  ) => {
    const startMinutes = parseInt(startHour) * 60 + parseInt(startMinute);
    const endMinutes = parseInt(endHour) * 60 + parseInt(endMinute);

    if (endMinutes <= startMinutes) {
      return {
        valid: false,
        message: '结束时间不能早于或等于开始时间',
      };
    }

    // 检查是否跨天（可选的业务逻辑）
    if (endMinutes < startMinutes) {
      return {
        valid: false,
        message: '暂不支持跨天营业时间',
      };
    }

    return { valid: true, message: '' };
  };

  // 处理时间选择变化
  const handleTimeChange = (e: any) => {
    if (disabled) return;

    const indices = e.detail.value;
    const [startHourIdx, , startMinuteIdx, , endHourIdx, , endMinuteIdx] =
      indices; // 跳过分隔符

    const startHour = simpleTimeRange[0][startHourIdx];
    const startMinute = simpleTimeRange[1][startMinuteIdx];
    const endHour = simpleTimeRange[2][endHourIdx];
    const endMinute = simpleTimeRange[3][endMinuteIdx];

    // 验证时间合理性
    const validation = validateTime(startHour, startMinute, endHour, endMinute);

    if (!validation.valid) {
      Taro.showToast({
        title: validation.message,
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    // 确保分隔符列始终为0，更新状态
    const correctedIndices = [
      startHourIdx,
      0, // : 分隔符固定为0
      startMinuteIdx,
      0, // ~ 分隔符固定为0
      endHourIdx,
      0, // : 分隔符固定为0
      endMinuteIdx,
    ];
    setSelectedIndices(correctedIndices);

    // 格式化并回调
    const newValue = `${startHour}:${startMinute}~${endHour}:${endMinute}`;
    onChange?.(newValue);
  };

  // 显示的文本
  const displayText = value || placeholder;
  const isPlaceholder = !value;

  // 计算并显示营业时长
  const getDurationText = () => {
    if (!value || !value.includes('~')) return '';
    const [start, end] = value.split('~');
    return calculateDuration(start, end);
  };

  return (
    <View className={styles.businessTimePicker}>
      <Picker
        mode="multiSelector"
        range={timeRange}
        rangeKey="label"
        value={selectedIndices}
        onChange={handleTimeChange}
        disabled={disabled}
      >
        <View
          className={`${styles.displayArea} ${disabled ? styles.disabled : ''}`}
        >
          <View className={styles.mainContent}>
            <Text
              className={`${styles.displayText} ${isPlaceholder ? styles.placeholder : ''} ${disabled ? styles.disabledText : ''}`}
            >
              {displayText}
            </Text>
            {showDuration && value && (
              <Text className={styles.durationText}>
                营业时长：{getDurationText()}
              </Text>
            )}
          </View>
        </View>
      </Picker>
    </View>
  );
};

export default BusinessTimePicker;
